using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public static Action<Enemy> OnEndReached;//敌人到达终点委托
    [SerializeField] private float moveSpeed = 3f;  // 控制敌人移动速度的参数
    [NonSerialized] public Waypoint waypoint;      // 敌人移动路径的路标点
    [NonSerialized] public float MoveSpeed;//保存移速
    public Vector3 CurrentPointPosition => waypoint.GetWaypointPosition(_currentWaypointIndex);//获取指定索引的路径点位置
    private int _currentWaypointIndex;  // 当前路标点的索引
    [NonSerialized] public EnemyHealth _enemyHealth;

    private Vector3 _lastPointPosition;
    private SpriteRenderer _spriteRenderer;

    private void Start()
    {
        _currentWaypointIndex = 0;  // 初始化当前路标点索引为0
        MoveSpeed = moveSpeed;

        _enemyHealth = GetComponent<EnemyHealth>();
        _spriteRenderer = GetComponent<SpriteRenderer>();

        _lastPointPosition = transform.position;
    }

    private void Update()
    {
        Move();  // 调用移动方法
        Rotate();
        if (CurrentPointPositionReached())
        {
            UpdateCurrentPointIndex();
        }
    }

    //控制转向
    private void Rotate()
    {
        if (CurrentPointPosition.x > _lastPointPosition.x)
        {
            _spriteRenderer.flipX = false;
        }
        else
        {
            _spriteRenderer.flipX = true;
        }
    }


    //移动敌人至下一个路径点
    private void Move()
    {
        // 使敌人向目标位置移动
        transform.position = Vector3.MoveTowards(transform.position,
                                                CurrentPointPosition,
                                                moveSpeed * Time.deltaTime);
    }

    //检查是否到达当前路径点的位置
    private bool CurrentPointPositionReached()
    {
        float distanceToNextPointPosition = (transform.position - CurrentPointPosition).magnitude;
        if (distanceToNextPointPosition < 0.1f)
        {
            _lastPointPosition = transform.position;
            return true;
        }
        return false;
    }

    //更新当前路径点的索引
    private void UpdateCurrentPointIndex()
    {
        int lastWaypointIndex = waypoint.Points.Length - 1;
        if (_currentWaypointIndex < lastWaypointIndex)
        {
            _currentWaypointIndex++;
        }
        else
        {
            ReturnEnemyToPool();//到达最后回收敌人
        }
    }

    //回收敌人
    private void ReturnEnemyToPool()
    {
        OnEndReached?.Invoke(this);
        _enemyHealth.ResetHealth();
        ObjectPooler.ReturnToPool(gameObject);
    }

    //重置寻路索引
    public void ResetEnemy()
    {
        _currentWaypointIndex = 0;
    }

    public void StopMovement()
    {
        moveSpeed = 0f;
    }

    public void ResumeMovement()
    {

        moveSpeed = MoveSpeed;
    }
}
